import pymysql

# 创建类
class DBUtil:

    @classmethod  # 装饰器 该装饰器下方法为类方法
    def __get_conn(cls):  # 私有属性
        # 创建连接
        conn = pymysql.connect(host="211.103.136.244", port=7061, user="student",
                               password="iHRM_student_2021", database="ihrm", charset="utf8")
        return conn

    @classmethod
    def select_one(cls, sql):
        cursor = None # 局部变量
        conn = None
        res = None
        try:
            conn = cls.__get_conn() # 用 cls(相当于类的对象) 调用连接方法
            cursor = conn.cursor() # 创建游标
            cursor.execute(sql) # 执行 用户 指定的 sql
            res = cursor.fetchone()  # sql 查询一条语句
            print("执行查询一条sql语句成功")
        except Exception as e:
            print("执行中查询一条sql语句记录时,报错:", str(e))
        finally:
            cursor.close() # 关闭游标
            conn.close() # 关闭连接
            return res

    @classmethod
    def idu_methods(cls, sql):
        conn = None  # 设置局部变量
        cursor = None
        try:
            conn = cls.__get_conn()  # 调用连接方法
            cursor = conn.cursor()  # 创建游标
            cursor.execute(sql)  # 执行 用户 指定的 sql
            conn.commit()  # 成功 提交事务
            print("增/删/改 sql语句:Affected rows:", conn.affected_rows())
        except Exception as e:
            print("执行sql增删改数据库,报错信息:", str(e))
            conn.rollback()  # 失败 回滚事务
        finally:
            cursor.close()
            conn.close()
#
if __name__ == '__main__':
    DBUtil.idu_methods("delete from bs_user where mobile = '13812344325';")